package com.ruoyi.scale.document.base;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.mongodb.repository.MongoRepository;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * 使用Example.of 不能使用 内部类方式创建对象
 * Example.of(new Scale(){{
 *    setRuleName("common");
 * }}); 会导致生成 调用类$1 ; 生成
 * { "ruleName" : "growthEvalRule", "_class" : { "$in" : ["com.scale.GrowImport$1"]}} fields: Document{{}} for class: class com.scale.GrowImport$1 in collection: scale
 * @param <T>
 */
public abstract class BaseDocumentService<T extends BaseDocumentDomain> {
    @Autowired
    private MongoRepository<T,String> mongoRepository;

    public MongoRepository<T,String> getMongoRepository(){
        return this.mongoRepository;
    }

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    public Optional<T> getById(String id){
        return mongoRepository.findById(id);
    }

    /**
     * 根据ID集合查询
     * @param ids
     * @return
     */
    public Iterable<T> getByIds(List<String> ids){
        return mongoRepository.findAllById(ids);
    }

    /**
     * 批量保存
     * @param entities
     * @return
     */
    public List<T> save(List<T> entities){
        return mongoRepository.saveAll(entities);
    }

    /**
     * 保存
     * @param entity
     * @return
     */
    public T save(T entity){
        return mongoRepository.save(entity);
    }

    /**
     * 根据实体删除
     * @param t
     */
    public void delete(T t){
        mongoRepository.delete(t);
    }

    /**
     * 根据实体集合删除
     * @param entities
     */
    public void delete(List<T> entities){
        mongoRepository.deleteAll(entities);
    }

    /**
     * 根据id集合删除
     * @param ids
     */
    public void deleteAllById(List<String> ids){
        mongoRepository.deleteAllById(ids);
    }

    /**
     * 根据id删除
     * @param id
     */
    public void  deleteById(String id){
        mongoRepository.deleteById(id);
    }


    public List<T> findAll(Example<T> example){
        return mongoRepository.findAll(example);
    }
}
